package com.medical.Controller.admin;


import com.medical.DTO.LoginDTO;
import com.medical.Service.EmployeeService;
import com.medical.VO.LoginVO;
import com.medical.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin("*")
@RequestMapping("/api")
@Tag(name = "用户管理类")
public class EmployeeLoginController {
    @Autowired
    private EmployeeService userService;

    @PostMapping("/admin/login")
    @Operation(summary = "管理员登录")
    public Result login(@RequestBody(required = true) LoginDTO loginDTO, HttpServletResponse response) {
        //登录信息为空，直接返回为空
        if (loginDTO.getUsername() == null || loginDTO.getPassword() == null ||
                loginDTO.getUsername().isEmpty() || loginDTO.getPassword().isEmpty()) {
            System.out.println("登录信息为空");
            return Result.error("登陆信息为空");
        }

        try {
            LoginVO loginVO = userService.login(loginDTO);

            if (loginVO == null) {
                System.out.println("登录失败：账号或密码错误");
                return Result.error("账号或密码错误");
            }

            // 将token添加到响应头，方便前端直接使用
            String token = loginVO.getToken();
            loginDTO.setToken(null);
            System.out.println("token:"+token);
            if (token != null && !token.isEmpty()) {
                // 在响应头中添加token
                response.setHeader("token", token);
                // 允许前端获取自定义header
                response.setHeader("Access-Control-Expose-Headers", "token");
            }

            System.out.println("登录成功:username=" + loginVO.getUsername() + ", token=" + (token != null ? "已生成:"+token : "为空"));

            return Result.success(loginVO);
        }catch (Exception e) {
            System.err.println("登录异常: " + e.getClass().getName() + ": " + e.getMessage());
            return Result.error("登录失败: " + e.getMessage());
        }
    }



}
